package com.roc.admin.infrastructure.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token配置类
 */
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册Sa-Token拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor(handle -> {
            // 登录校验 - 拦截所有需要登录的接口
            SaRouter.match("/**")
                    // 排除登录接口
                    .notMatch("/auth/login")
                    // 排除Swagger相关接口
                    .notMatch("/swagger-ui.html"
                            , "/swagger-ui/**"
                            , "/swagger-resources/**"
                            , "/v3/api-docs/**"
                            , "/v3/api-docs"
                            , "/api-docs/**"
                            , "/api-docs"
                            , "/api-docs.yaml"
                            , "/favicon.ico"
                            , "/doc.html"
                            , "/doc.html/**")
                    // 排除Knife4j相关接口
                    .notMatch("/webjars/**"
                            , "/swagger-config/**"
                            , "/knife4j/**"
                            , "/doc.html/**")
                    // 排除静态资源
                    .notMatch("/static/**"
                            , "/resources/**"
                            , "/public/**")
                    // 排除错误页面
                    .notMatch("/error")
                    // 执行校验
                    .check(r -> StpUtil.checkLogin());
            
            // 权限校验 - 不同接口不同权限
            SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
            SaRouter.match("/role/**", r -> StpUtil.checkPermission("role"));
            SaRouter.match("/menu/**", r -> StpUtil.checkPermission("menu"));
            SaRouter.match("/dept/**", r -> StpUtil.checkPermission("dept"));
        })).addPathPatterns("/**");
    }
}
